package com.yuchen.jaxrs.restclient;


import org.apache.commons.lang.StringUtils;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jack Q
 */
public class RestClientUtils {


    public static String url(String url, Map<String, Object> params) {
        if (StringUtils.isNotBlank(url)) {
            if (null != params && !params.isEmpty()) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    url = url.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue().toString());
                }
            }
        }
        return url;
    }


    public static <T> T get(final Class<T> t, final String url) {
        return (T) new RestEasyClientTemplate() {
            @Override
            public Object doProcess(ResteasyWebTarget target) {
                Response r = target.request().get();
                T entity = r.readEntity(t);
                r.close();
                return entity;
            }
        }.process(url);
    }

    public static  <T> List<T> get(final GenericType<T> genericType,final String url) {
        return (List<T>)  new RestEasyClientTemplate() {
            @Override
            public Object doProcess(ResteasyWebTarget target) {
                Response r = target.request().get();
                List<T> entity= (List<T>) r.readEntity(genericType);
                r.close();
                return entity;
            }
        }.process(url);
    }



    public static <T> T post(final Class<T> t,final Object param, final String url) {
        return (T) new RestEasyClientTemplate() {
            @Override
            public Object doProcess(ResteasyWebTarget target) {
                Response r = target.request().post(Entity.entity(param, MediaType.APPLICATION_JSON_TYPE));
                T entity = r.readEntity(t);
                r.close();
                return entity;
            }
        }.process(url);
    }



    public static <T> T delete(final Class<T> t, final String url) {
        return (T) new RestEasyClientTemplate() {
            @Override
            public Object doProcess(ResteasyWebTarget target) {
                Response r = target.request().delete();
                T entity = r.readEntity(t);
                r.close();
                return entity;
            }
        }.process(url);
    }



    public static void main(String[] args) {
        String url = "http://localhost:8889/services/orderCommentService/find/{orderId}/pager/{pageNo}/{pageSize}";
        Map map = new HashMap();
        map.put("orderId", 1);
        url = RestClientUtils.url(url, map);
        System.out.println(url);
    }
}
